using System;
using System.Collections;
using System.Collections.Generic;
using Life.UI.MVC.Controller;
using Life.UI.MVC.Loader;
using UnityEngine;
using ControllerTypeValue = System.Int32;

namespace Life.UI.MVC.Example
{
    public class SceneLocalUILoader : UILoader
    {
        [SerializeField]GameObject[] _uiPrefabs;

        private Dictionary<ControllerTypeValue, GameObject> _uiMapping;
        
        protected override void OnInitialize(Action callback)
        {
            if (_uiPrefabs is { Length: > 0 })
            {
                _uiMapping = new Dictionary<ControllerTypeValue, GameObject>(_uiPrefabs.Length);
                foreach (var item in _uiPrefabs)
                {
                    var key = item.GetComponent<ControllerBase>().TargetControllerType;
                    _uiMapping.Add(key, item);
                }
            }
            callback?.Invoke();
        }

        public override GameObject Load(ControllerTypeValue token)
        {
            if (_uiMapping == null)
            {
                Debug.LogError("No UI Prefabs found");
            }
            if (_uiMapping.TryGetValue(token, out var ui))
            {
                return Instantiate(ui);
            }
            return null;
        }
    }
}

